<template>
    <div id="authority">
        <!--搜索框-->
        <div class="interview-header">
            <el-form ref="searchItem" :model="searchItem" :inline="true"  class="demo-form-inline">
                <el-form-item label="角色名" class="search-item" prop="name">
                    <el-input v-model="searchItem.name" placeholder="角色名"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="fa-search" @click="loadData(searchItem.name, pageNum, pageSize)">查询</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button icon="fa-repeat" @click="resetForm('searchItem')">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!--列表-->
        <div class="au-container">
            <div class="auth-list" v-show="isShowList">
                <div class="salesman-tree">
                    <div class="salesman-tree-btn">
                        <el-button type="primary" class="salesman-tree-save" @click="changeUserAuthTree">确定</el-button>
                        <el-button class="salesman-tree-save" @click="isShowList = false">关闭</el-button>
                    </div>
                    <el-tree
                    ref="tree"
                    :data="treeData"
                    :default-expand-all="true"
                    show-checkbox
                    node-key="id"
                    :default-checked-keys="checkedArr"
                    @node-click="clickTree"
                    @check-change="checkChange"
                    ></el-tree>
                </div>
            </div>
            <div class="g-table" ref="table" v-bind:class="{ tableWidth: isShowList }">
                <div class="table-box">
                    <el-table border :data="tableData">
                        <el-table-column align="center" label="角色名" prop="name"></el-table-column>
                        <el-table-column align="center" label="备注"></el-table-column>
                        <el-table-column align="center" label="状态" prop="status"></el-table-column>
                        <el-table-column align="center" label="操作" >
                            <template scope="scope">
                                <el-button size="small" @click="showList(scope.row)"  :disabled="scope.row.id === 1?true:false">权限管理</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <!--分页-->
        <div class="pageNum">
            <el-pagination
                :current-pageNum="pageNum"
                :page-sizes="[10, 30, 45]"
                :page-size="pageSize"
                layout="prev, pager, next, total, sizes"
                :total="total"
                @current-change="currentChange"
                @size-change="sizeChange"
                >
            </el-pagination>
        </div>
    </div>
</template>

<script>
/* eslint-disable */
    import axo from "@/assets/js/axo";
    export default {
        name: "authority",
        data () {
            return {
                checkedRow: [],
                checkedArr: [],
                isShowList: false,
                searchItem: {
                    name: "",
                },
                tableData: [],
                treeData: [{
                    id: "0000",
                    label: '借款管理平台',
                    type: "1",
                    remark: "",
                    children: [{
                        id: "0002",
                        label: '借款管理',
                        children: []
                    }]
                }],
                treeArr: [],
                treeArrRecord: [],
                pageNum: 1,
                pageSize: 10,
                total: 0,
            };
        },
        methods: {
            test () {
                console.log([...this.treeArr]);
            },
            currentChange (val) {
                this.pageNum = val;
                console.log(`当前页: ${val}`);
                this.loadData(this.searchItem.name, val, this.pageSize);
            },
            sizeChange (val) {
                this.pageSize = val;
                this.loadData(this.searchItem.name, this.pageNum, val);
                console.log(`每页 ${val} 条`,';总数：', this.total);
            },
            resetForm (item) {
                this.$refs[item].resetFields();
            },
            checkChange (data, checked, indeterminate) {
                /**
                 * 节点选中状态发生变化时的回调
                 * @param data           节点对象
                 * @param checked        本身是否给选中
                 * @param indeterminate  节点的子树中是否有被选中的节点
                 * @type {[type]}
                 */
                // console.log(JSON.parse(JSON.stringify(data)));
                // console.log(checked);
                // console.log(indeterminate);
                let treeArr = [...this.treeArr];
                treeArr = treeArr.map((ele,index, arr) => {
                    // 改变子节点选中状态
                    if(ele.id === data.id && ele.type === "2"){
                        ele.check = checked?"1":"0";
                        function tickDirectory(pid) {
                            if(pid !== '0000'){
                                let isChecked = arr.some((el, ind ) => {
                                    if(pid === el.pid && el.check === '1'){
                                        return true;
                                    }
                                });
                                arr.forEach((e, i) => {
                                    if(e.id === pid ) {
                                        if(isChecked){
                                            // console.log('>>>>>>>>', JSON.parse(JSON.stringify(e)));
                                            arr[i].check = '1';
                                        }else{
                                            arr[i].check = '0';
                                        }
                                        // 递归判断任何目录是否优子节点被选中
                                        tickDirectory(e.pid)
                                    }
                                });
                            }
                        }
                        tickDirectory(data.pid)
                    }
                    // 改变目录状态
                    if(ele.id === data.id && ele.type === "1"){
                        // console.log('改变目录状态');
                        if( indeterminate || checked ){
                            ele.check = "1";
                        }else{
                            ele.check = "0";
                        }
                    }
                    return ele;
                });
                console.log(JSON.parse(JSON.stringify(treeArr)));
                // console.log(treeArr);
                this.treeArrRecord = treeArr;
            },
            changeUserAuthTree () {
                let authTree = this.treeArrRecord;
                let a = JSON.stringify(authTree);
                let b = JSON.parse(a);
                console.log('authTree', b);
                let newAuthTree = [];
                authTree.forEach((ele, index) => {
                    if(ele.check === "1"){
                        let obj = {};
                        obj.code = ele.id;
                        obj.type = ele.type;
                        obj.name = ele.name;
                        obj.remark = ele.remark;
                        newAuthTree.push(obj);
                    }
                });
                console.log('newAuthTree', newAuthTree);
                axo({
                    method: "post",
                    url: "/api-sys/rolePermission/add",
                    data: {
                        "platformNo": "1",
                        "body": {
                            "roleNo": this.checkedRow.roleNo,
                            "roleName": this.checkedRow.name,
                            "roleList": newAuthTree
                        }
                    }
                }).then((res) => {
                    if(res.data.state.code === "200"){
                        this.$message({
                            type: "success",
                            message: "修改成功",
                            duration: 800
                        });
                        this.showList(this.checkedRow);
                    }
                    console.log(res);
                });
            },
            clickTree(self, node) {
                console.log(self);
            },
            async showList (row) {
                await this.$refs.tree.setCheckedKeys([]);
                this.checkedRow = row;
                this.isShowList=true;
                let CheckedKeysArr = [];
                function traversal(tree=[],pid="0000"){
                    let ye=[];

                    tree.forEach((ele,index,arr) => {
                        if(ele.pid===pid && ele.type==="1"){
                            let item = {};
                            item.id = ele.id;
                            item.label = ele.name;
                            item.pid = ele.pid;
                            item.remark = ele.remark?ele.remark:"";
                            item.type = ele.type;
                            item.url = ele.url?ele.url:"";
                            item.check = ele.check;
                            item.children = traversal(tree,item.id);
                            ye.push(item);
                        }
                        if(ele.pid===pid && ele.type==="2"){
                            let item = {};
                            item.id = ele.id;
                            item.label = ele.name;
                            item.pid = ele.pid;
                            item.remark = ele.remark?ele.remark:"";
                            item.type = ele.type;
                            item.url = ele.url?ele.url:"";
                            item.check = ele.check;
                            ye.push(item);
                        }
                    });
                    return ye;
                }
                /**
                 * 判断有没子树
                 * @param  {Array}   [tree=[]] [description]
                 * @param  {[type]}  id        [description]
                 * @return {Boolean}           [description]
                 */
                function hasSubtree (tree=[], id) {
                    let bool = tree.some((ele) => {
                        if(ele.pid == id ){
                            return true;
                        }
                        return false;
                    });
                    return bool;
                }
                // 请求数据接口
                await axo({
                    method: "post",
                    url: "/api-sys/menu/queryMenuTreeAndCheck",
                    data: {
                        "platformNo": "1",
                        "body": {
                            "role_no": row.roleNo
                        }
                    }
                }).then((res) => {
                    console.log(JSON.parse(res.data.ciphertext));
                    let treeArrList = JSON.parse(res.data.ciphertext);

                    this.treeArr = treeArrList;
                    this.treeArrRecord = treeArrList;

                    this.treeData[0].children = traversal(treeArrList,"0000");

                    // 勾选节点
                    treeArrList.forEach((ele,index) => {
                        if(ele.check === "1" && ele.type === "2"){
                            CheckedKeysArr.push(ele.id);
                        }
                        if(ele.check === "1" && ele.type === "1"){
                            if(!hasSubtree(treeArrList, ele.id)){
                                CheckedKeysArr.push(ele.id);
                            }
                        }
                    });
                }).catch((e) => {
                    console.log(e);
                });
                console.log("CheckedKeysArr", CheckedKeysArr);
                this.$refs.tree.setCheckedKeys(CheckedKeysArr);
            },
            async loadData (name='', pageNum=1, pageSize=10) {
                await axo({
                    method: 'post',
                    url: '/api-sys/role/queryRoleList',
                    data: {
                        "body": {
                            name: name,
                            pageNum: pageNum,
                            pageSize: pageSize
                        }
                    }
                }).then((res) => {
                    console.log(res);
                    let ciphertext = JSON.parse(res.data.ciphertext);
                    this.total = ciphertext.total;
                    this.tableData = ciphertext.list.map((ele,i) => {
                        if(ele.status === 1){
                            ele.status = "有效";
                        }
                        if(ele.status === 0){
                            ele.status = "无效";
                        }
                        return ele;
                    });
                }).catch((e) => {
                    console.log(e);
                });
            }
        },
        mounted: function () {
            this.$nextTick(function () {
                this.loadData();
            });
        }
    };
</script>

<style lang="scss" scoped="true">
    #authority .au-container{
        display: flex;
        margin: 0 20px;
        .g-table{
            width: 100%;
        }
        .tableWidth{
            width: 85%;
        }
    }
    .auth-list{
        margin-right: 10px;
        min-width: 200px;
        width: 15%;
        box-shadow: 3px 3px 4px 3px rgba(252, 247, 247, 0.85);
        .el-tree{
            border: none;
        }
    }
    #authority{
        .interview-header{
            border: 1px solid #eee;
            margin:20px;
            padding:22px 0 0 20px;
            min-width: 1200px;
            box-sizing: border-box;
            .search-in{
                .search-item{
                    margin-right: 30px;
                }
            }
        }
        .table-box{
            // width: 100%;
            border: 1px solid #eee;
            // min-width: 1200px;
            .add-btn{
                margin: 20px;
                .el-icon-plus{
                    font-size:12px;
                }
            }
        }
        .el-table .cell, .el-table th>div{
            padding:5px;
            white-space: nowrap;
        }
        .pageNum{
            text-align: right;
            padding: 10px;
            .el-pagination{
                padding:0;
            }
        }
    }
    .salesman-tree-btn{
        padding: 15px 0;
        text-align: center;
    }
</style>
